package netty_chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 聊天室服务端
 */
public class NettyChatServer {

    private int port; // 端口号

    public NettyChatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {
            // 1.创建bossGroup线程组: 处理网络事件--连接事件
            bossGroup = new NioEventLoopGroup(1);
            // 2.创建workerGroup线程组: 处理网络事件--读写事件
            workerGroup = new NioEventLoopGroup();
            // 3.创建服务端启动助手
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 4.设置线程组
            bootstrap.group(bossGroup, workerGroup);
            // 5.设置服务端通道实现
            bootstrap.channel(NioServerSocketChannel.class)
                    // 6.参数设置-设置线程队列中等待连接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 6.参数设置-设置活跃状态,child是设置workerGroup
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    // 7.创建一个通道初始化对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            // 添加编解码器
                            sc.pipeline().addLast(new StringDecoder());
                            sc.pipeline().addLast(new StringEncoder());
                            // 8.向pipeline中添加自定义业务处理handler
                            sc.pipeline().addLast(new NettyChatServerHandler());
                        }
                    });
            // 9.启动服务端并绑定端口，同时将异步改为同步
            ChannelFuture future = bootstrap.bind(port).sync();

            System.out.println("聊天室服务端启动成功.");
            // 10.关闭通道(并不是真正意义上的关闭,而是监听通道关闭状态)和关闭连接池
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyChatServer(9998).run();
    }
}
